#!/usr/bin/env python
# -*- coding: utf-8 -*-
from extend import Master, Worker
from dm_py_util import DEBUG_LOG, ERROR_LOG


class HTTPWorker(Worker):

    def init(self, config):
        self.init_worker(config)

    def init_worker(self, config):
        pass


class HTTPServer(Master):

    def __init__(self, worker=HTTPWorker, main_config=''):
        super(HTTPServer, self).__init__(
            worker=worker, main_config=main_config)

    def run(self):
        self.__init_master__(self.config)
        self.serve_forever()

    def __init_master__(self, config):
        from ConfigParser import ConfigParser
        cfg = ConfigParser()
        cfg.read(config)
        self.locations = eval(cfg.get('HTTP', 'locations'))
        self.locations = self.locations or '/'

    def init_master(self, config):
        DEBUG_LOG('init master')

    def init_server(self):
        import tornado.httpserver
        import tornado.web
        handlers = self.install_handler()
        if not handlers:
            DEBUG_LOG('handlers', handlers)
            raise Exception('HTTPServer handlers in null')
        handler = list(zip(self.locations, handlers))
        if not handler:
            raise Exception('HTTPServer no handler')
        app = tornado.web.Application(handler)
        server = tornado.httpserver.HTTPServer(app, xheaders=True)
        return server

    def install_handler(self):
        return []
